import React, { Component } from 'react';
import {Link, withRouter} from 'react-router-dom'
import {Menu, Icon} from 'antd';
import logo from '../../assets/images/logo.png'
import menuList from '../../config/menuConfig'
import './left-nav.less'
import memoryUtils from "../../utils/memoryUtils";
const { SubMenu } = Menu;
 class LeftNav extends Component {

  constructor(props) {
    super(props);
    this.state={

    }
    this.openKey='';
    }

  //判断是否有权限
  hasAuth = (item) => {
    const {key, isPublic} = item
    // console.log("key",key);
    const menus = memoryUtils.user.role.menus
    const username = memoryUtils.user.username
    // console.log(menus);
    /*
    1. 如果当前用户是admin
    2. 如果当前item是公开的
    3. 当前用户有此item的权限: key有没有menus中
     */
    if(username==='admin' || isPublic || menus.indexOf(key)!==-1) {
      return true
    } else if(item.children){ // 4. 如果当前用户有此item的某个子item的权限
      // console.log(item.children);
      return !!item.children.find(child =>  menus.indexOf(child.key)!==-1)
    }

    return false
  }

  //渲染子节点
  getMenuNodes=(menuList)=>{
    // console.log(123);
    let path = this.props.location.pathname


   return menuList.map((item,index)=>{
     if(this.hasAuth(item)){
       if(item.children){
         const cItem = item.children.find(cItem => path.indexOf(cItem.key)===0)
         if(cItem){
           this.openKey=item.key
         }
          return(
           <SubMenu title={item.title} key={item.key} icon={item.icon}>
            { this.getMenuNodes(item.children)}
           </SubMenu>
          )
       }else{
         return(
           <Menu.Item key={item.key} icon={item.icon}>
             <Link to={item.key}>{item.title}</Link>
           </Menu.Item>
         )
       }
     }
    })
  }


  
 async componentWillMount(){
   this.menuListModel= this.getMenuNodes(menuList)
  }
  render() {
      let path = this.props.location.pathname
      console.log(path);
      if(path.indexOf('/product')===0){
        path='/product'
      }
    return (
      <div className="left-nav">
        <Link to='/' className="left-nav-header">
          <img src={logo} alt="logo"/>
          <h1>后台管理</h1>
        </Link>
         <Menu
          selectedKeys={[path]}
          defaultOpenKeys={[this.openKey]}
          mode="inline"
          theme="dark"
        >
          {  this.menuListModel}
        </Menu>
      </div>
    )
  }
}

export default withRouter(LeftNav)